<template>
  <div class="wheel">
    <LuckyWheel
        ref="myLucky"
        width="500px"
        height="500px"
        :prizes="data.prizes"
        :blocks="blocks"
        :buttons="buttons"
        :speed="speed"
        :accelerationTime="accelerationTime"
        :decelerationTime="decelerationTime"
        @start="startCallback"
        @end="endCallback"
    />
  </div>

  <div style="margin-top: 5vh;margin-left: 10vw">
    <a-select
        style="min-width: 300px"
        v-model:value="words"
        mode="tags"
        placeholder="输入数组元素"
        :max-tag-count="20"
        :max-tag-text-length="10"
        :token-separators="words"
        allow-clear
        show-search
    />
    <a-button @click="resetSpinner">
      重置
    </a-button>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'

// 使用ref引用LuckyWheel组件
const myLucky = ref(null)

let words = ref(['Hello', 'B', 'C', 'D'])

// 使用reactive定义响应式数据
const data = reactive({
  speed: 100,           // 初始速度，值越大转得越快
  accelerationTime: 1000, // 加速时间(毫秒)
  decelerationTime: 2000, // 减速时间(毫秒)
  blocks: [
    {padding: '10px', background: '#869cfa'}
  ],
  prizes: [
    {background: '#e9e8fe', fonts: [{text: 'Hello'}]},
    {background: '#b8c5f2', fonts: [{text: 'B'}]},
    {background: '#e9e8fe', fonts: [{text: 'C'}]},
    {background: '#b8c5f2', fonts: [{text: 'D'}]},
    {background: '#e9e8fe', fonts: [{text: 'E'}]},
    {background: '#b8c5f2', fonts: [{text: 'F'}]},
  ],
  buttons: [
    {radius: '40%', background: '#617df2'},
    {radius: '35%', background: '#afc8ff'},
    {
      radius: '30%', background: '#869cfa',
      pointer: true,
      fonts: [{text: '开始', top: '-10px'}]
    }
  ]
})

// 解构数据以便在模板中直接使用
const {blocks, prizes, buttons, speed, accelerationTime, decelerationTime} = data

// 定义方法
const startCallback = () => {
  // 调用抽奖组件的play方法开始游戏
  myLucky.value.play()
  // 模拟调用接口异步抽奖
  setTimeout(() => {
    // 假设后端返回的中奖索引是0
    let backIndex = Math.floor(Math.random() * prizes.length);
    // 调用stop停止旋转并传递中奖索引
    myLucky.value.stop(backIndex)
  }, 2500)
}

// 抽奖结束会触发end回调
const endCallback = (prize) => {
  console.log(prize)
}

const resetSpinner = function () {
  let prizeArr = [];
  const colors = ['#e9e8fe', '#b8c5f2']; // 添加颜色交替

  for (let i = 0; i < words.value.length; i++) {
    let prize = {
      background: colors[i % colors.length],
      fonts: [{text: words.value[i]}]
    }
    prizeArr.push(prize);
  }

  data.prizes = prizeArr;
}
</script>

<style scoped>
.wheel {
  margin-left: 10vw;
  margin-top: 5vh;
}
</style>